package com.bee.bootstrap.system.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.bee.bootstrap.system.entity.Sequence;
import com.bee.bootstrap.system.mapper.SequenceMapper;
import com.bee.bootstrap.system.service.ISequenceService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liekkas
 * @since 2018-04-11
 */
@Service
public class SequenceServiceImpl extends ServiceImpl<SequenceMapper, Sequence> implements ISequenceService {


    @Override
    public String saveSeqGenerator(String tableName, String column, String format,int start) {
        Sequence condition=new Sequence();
        condition.setTableName(tableName);
        condition.setColumnName(column);
        Sequence persistence=this.selectOne(new Wrapper<Sequence>() {
            @Override
            public String getSqlSegment() {
                return "where table_name='"+tableName+"' AND column_name='"+column+"' for update";
            }
        });
        if(persistence==null){
            Sequence seq=new Sequence();
            seq.setTableName(tableName);
            seq.setColumnName(column);
            seq.setNextVal(start);
            this.insert(seq);
            persistence=seq;
        }
        int currentVal=persistence.getNextVal();
        persistence.setNextVal(currentVal+1);
        this.updateById(persistence);
        if(!StringUtils.isEmpty(format)){
            return String.format(format,currentVal);
        }
        return String.valueOf(currentVal);
    }


}
